//
//  M_NewsListVC.swift
//  letuofu
//
//  Created by WH-JS on 2019/12/24.
//  Copyright © 2019 WH-JS. All rights reserved.
//

import UIKit
import MJRefresh

class M_NewsListVC: BaseViewControllerWithHeader, UITableViewDelegate, UITableViewDataSource{
    var pageIndex = 1
    var pageSize = 10
    var totalSize = 10
    var news = [[String:Any?]]()
    
    var tableView = UITableView(frame: CGRect.zero, style: .plain)
    override func viewDidLoad() {
        super.viewDidLoad()
        UIApplication.shared.applicationIconBadgeNumber = 0

        getNewsList {
        }
        //设置应用程序右上角的提醒个数
        safeView.addSubview(tableView)
        // Do any additional setup after loading the view.
        setupUI()
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        //退出消息窗口的时候重新设置已读状态
        UnreadPointForNewsButton.checkUpdateUnreadFlag(point: nil)
    }
    
    func deleteNews(id: Int)  {
        API.formRequest(url: .A_delSyspushdesc, params: ["ids":"\(id)"]) { (result) in
            if result.success {
                
            } else {
                
            }
        }
    }
    func getNewsList(callback:  @escaping () -> Void) {
        API.formRequest(url: .A_SyspushdescList, params: ["pageIndex":"\(pageIndex)","pageNum":"\(pageSize)", "guid":LocalStorage.getString(forKey: USER_GUID)!], callback: { (result) in
            if result.success {

                if self.pageIndex == 1 {
                    self.news.removeAll()
                }
               
                if let dl = result.data?.getDictList("data") {
                    self.news.append(contentsOf: dl)
                    self.tableView.reloadData()
                    if let number = result.data?.getInt("allCount") {
                        self.totalSize = number

                    }
                    
                    callback()
                }
                else {
                }
            }
        })
    }
}


// MARK: UI
extension M_NewsListVC {
    func setupUI() {
        safeView.backgroundColor = .xF2F2F2
        headView.backgroundColor = .white
        headTitle.text = "通知消息"
        
        safeView.addSubview(tableView)
        tableView.register(UINib.init(nibName: "NewsListTableViewCell", bundle: nil) , forCellReuseIdentifier: "newsList")
        tableView.backgroundColor = UIColor.clear;
        tableView.separatorStyle = .none
        tableView.dataSource = self
        tableView.delegate = self
        tableView.allowsMultipleSelection = true
//        tableView.estimatedSectionFooterHeight = 52
//        tableView.sectionFooterHeight = UITableView.automaticDimension
        tableView.snp.makeConstraints { (make) in
            make.top.equalTo(headView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
        let _ = getRefreshHeader()
        
       let _ = getRefreshFooter()

    }
    
        func getRefreshHeader()->MJRefreshHeader {
    //        顶部的下拉初始化
            let header = MJRefreshNormalHeader()
            header.lastUpdatedTimeLabel.isHidden = true
            tableView.mj_header = header
            header.setTitle("下拉刷新...", for: .idle)
            header.setTitle("下拉刷新...", for: .pulling)
            header.setTitle("下拉更新中...", for: .refreshing)
            header.setTitle("完成...", for: .willRefresh)
            header.setTitle("下拉刷新...", for: .noMoreData)
            header.setRefreshingTarget(self, refreshingAction: #selector(onHeaderRequery))

    //        顶部的处理逻辑：
            return tableView.mj_header!
        }
        
        func getRefreshFooter()->MJRefreshFooter {
            if tableView.mj_footer == nil {
                //        底部初始化：
                let footer = MJRefreshBackNormalFooter()
    //            footer.isOnlyRefreshPerDrag = true
                tableView.mj_footer = footer
                footer.setTitle("上拉更多...", for: .idle)
                footer.setTitle("上拉更多...", for: .pulling)
                footer.setTitle("下拉更新中....", for: .refreshing)
                footer.setTitle("完成...", for: .willRefresh)
                footer.setTitle("没有了...", for: .noMoreData)
                footer.setRefreshingTarget(self, refreshingAction: #selector(onFooterLoadMore))
            }

    //        底部处理逻辑：
//            if pageIndex * pageSize < totalSize {
//                tableView.mj_footer.endRefreshing()
//            }
//            else {
//                tableView.mj_footer.endRefreshingWithNoMoreData()
//            }
            
    //        底部数据加载
             return tableView.mj_footer!
        }
}

// MARK: event & action
extension M_NewsListVC {
    @objc func onHeaderRequery() {
    //        顶部数据重新加载
    //        getRefreshFooter().state = .idle
    tableView.mj_header.endRefreshing()
        pageIndex = 1
        getNewsList {
        }
    }
    
    @objc func onFooterLoadMore() {
        //        底部数据重新加载更多底部处理逻辑：
        pageIndex += 1

        getNewsList {
            if self.pageIndex * self.pageSize < self.totalSize {
                self.tableView.mj_footer.endRefreshing()
            }
            else {
                self.tableView.mj_footer.endRefreshingWithNoMoreData()
            }
        }

    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return news.count
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 10
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let v = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 10))
        v.backgroundColor = .xF5F5F5
        
        return v
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 141
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "newsList", for: indexPath) as! NewsListTableViewCell
        
        cell.titleLabel.text = news[indexPath.section].getString("title")
        let attributedString = AttributHelper.setAttributedString(news[indexPath.section].getString("subtitle") ?? "", color: .x666666)
        cell.timeLabel.text = news[indexPath.section].getString("gmtModify")
        cell.contentLabel.attributedText = attributedString;
        return cell
        
    }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return false
    }
    
        func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
            let del = UITableViewRowAction(style: .default, title: "删除") { action, index in
                let newsT = self.news[indexPath.section]
                self.deleteNews(id: newsT.getInt("id") ?? 0)
                self.news.remove(at: indexPath.section)
                let indexS = NSIndexSet(index: indexPath.section)
                
                
                tableView.deleteSections(indexS as IndexSet, with: UITableView.RowAnimation.none)
            }

            del.backgroundColor = .red
            return [del]
        }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        NewsAction().go(from: self, news: news[indexPath.section])
    }
}
